import React, { useRef, useEffect } from "react";
import "jsoneditor/dist/jsoneditor.min.css";

export default function JsonEditorClient({ json, onJsonChange }) {
  const containerRef = useRef(null);
  const editorRef = useRef(null);

  useEffect(() => {
    let JSONEditor;
    let instance;
    let destroyed = false;
    import("jsoneditor").then((mod) => {
      if (destroyed) return;
      JSONEditor = mod.default;
      instance = new JSONEditor(containerRef.current, {
        mode: "code",
        mainMenuBar: false,
        onChange: () => {
          try {
            const updated = instance.get();
            onJsonChange(updated);
          } catch (e) {}
        }
      });
      instance.set(json);
      editorRef.current = instance;
    });
    return () => {
      destroyed = true;
      if (editorRef.current) {
        editorRef.current.destroy();
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (editorRef.current) {
      editorRef.current.update(json);
    }
  }, [json]);

  return <div ref={containerRef} className="h-[calc(100vh-120px)]" />;
}